package com.yan.config;


import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.yan.entity.Result;
import com.yan.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

@Component
public class ConsumerListener {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    public Set<String> productNames = new HashSet<>();

    public Set<String> success = new HashSet<>();

    @RabbitListener(queues = RabbitConstants.ORDER_QUEUE_NAME)
    public void getDirectMessage(Channel channel, Message message) throws IOException {
        String msg = new String(message.getBody());
        log.info("【mq接收到的消息】：{}", msg);
        try {
            Result result = JSON.parseObject(msg, Result.class);
            if (DateUtils.lte(DateUtils.parseDate(result.getExpireDate()), new Date())) {
                // 已过期
                // 拒绝消息，requeue=false 表示不再重新入队，如果配置了死信队列则进入死信队列
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
                log.info("【mq接收到的消息 已过期】");
                return;
            }
            String productName = result.getProductName();
            //未过期
            if (productNames.remove(productName)) {
                // 确认收到消息，false只确认当前consumer一个消息收到，true确认所有consumer获得的消息
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                success.add(productName);
                log.info("【mq接收到的消息 确认收到消息】");
            } else {
                // requeue为是否重新回到队列，true重新入队
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                log.info("【mq接收到的消息 消息即将再次返回队列处理】");
            }
        } catch (Exception e) {
            // requeue为是否重新回到队列，true重新入队
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            log.info("【mq接收到的消息 消息即将再次返回队列处理 catch】");
        }
    }
}
